package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.Article;
import com.example.forum.model.ArticleDraft;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.services.IArticleDraftService;
import com.example.forum.services.IBoradService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotNull;
import java.util.List;

@RestController
@Slf4j
@Api(tags = "文章草稿接口")
@RequestMapping("/article/draft")
public class ArticleDraftController {

    @Resource
    private IArticleDraftService articleDraftService;
    
    @Resource
    private IBoradService boardService;
    
    @ApiOperation("保存草稿")
    @PostMapping("/save")
    public AppResult<Long> saveDraft(
            HttpServletRequest request,
            @ApiParam("草稿ID，新建时不传") @RequestParam(value = "id", required = false) Long id,
            @ApiParam("板块ID") @RequestParam("boardId") @NotNull Long boardId,
            @ApiParam("草稿标题") @RequestParam("title") String title,
            @ApiParam("草稿内容") @RequestParam("content") String content,
            @ApiParam("文章标签") @RequestParam(value = "tags", required = false) String tags,
            @ApiParam("文章摘要") @RequestParam(value = "summary", required = false) String summary) {
        
        // 获取当前用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        
        // 校验用户状态
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        
        // 校验板块
        Board board = boardService.selectById(boardId);
        if (board == null || board.getDeleteState() == 1 || board.getState() == 1) {
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        
        // 创建或更新草稿
        ArticleDraft draft = new ArticleDraft();
        if (id != null) {
            draft.setId(id);
        }
        draft.setUserId(user.getId());
        draft.setBoardId(boardId);
        draft.setTitle(title);
        draft.setContent(content);
        draft.setTags(tags);
        draft.setSummary(summary);
        
        try {
            Long draftId = articleDraftService.saveDraft(draft);
            return AppResult.success(draftId);
        } catch (Exception e) {
            log.error("保存草稿失败", e);
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
    }
    
    @ApiOperation("获取草稿详情")
    @GetMapping("/detail/{id}")
    public AppResult<ArticleDraft> getDraftDetail(
            HttpServletRequest request,
            @ApiParam("草稿ID") @PathVariable("id") @NotNull Long id) {
        
        // 获取当前用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        
        try {
            ArticleDraft draft = articleDraftService.getDraftById(id);
            
            // 验证草稿所有权
            if (!draft.getUserId().equals(user.getId())) {
                return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
            }
            
            // 设置是否为草稿所有者
            draft.setOwn(true);
            
            return AppResult.success(draft);
        } catch (Exception e) {
            log.error("获取草稿详情失败", e);
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
    }
    
    @ApiOperation("获取用户所有草稿")
    @GetMapping("/list")
    public AppResult<List<ArticleDraft>> getUserDrafts(HttpServletRequest request) {
        
        // 获取当前用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        
        try {
            List<ArticleDraft> drafts = articleDraftService.getUserDrafts(user.getId());
            
            // 设置所有草稿的所有者标记
            for (ArticleDraft draft : drafts) {
                draft.setOwn(true);
            }
            
            return AppResult.success(drafts);
        } catch (Exception e) {
            log.error("获取用户草稿列表失败", e);
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
    }
    
    @ApiOperation("删除草稿")
    @PostMapping("/delete/{id}")
    public AppResult<Void> deleteDraft(
            HttpServletRequest request,
            @ApiParam("草稿ID") @PathVariable("id") @NotNull Long id) {
        
        // 获取当前用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        
        try {
            // 先获取草稿，验证所有权
            ArticleDraft draft = articleDraftService.getDraftById(id);
            
            if (!draft.getUserId().equals(user.getId())) {
                return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
            }
            
            boolean success = articleDraftService.deleteDraft(id);
            if (success) {
                return AppResult.success();
            } else {
                return AppResult.failed(ResultCode.ERROR_SERVICES);
            }
        } catch (Exception e) {
            log.error("删除草稿失败", e);
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
    }
    
    @ApiOperation("发布草稿")
    @PostMapping("/publish/{id}")
    public AppResult<Long> publishDraft(
            HttpServletRequest request,
            @ApiParam("草稿ID") @PathVariable("id") @NotNull Long id) {
        
        // 获取当前用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        
        // 校验用户状态
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        
        try {
            // 先获取草稿，验证所有权
            ArticleDraft draft = articleDraftService.getDraftById(id);
            
            if (!draft.getUserId().equals(user.getId())) {
                return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
            }
            
            // 发布草稿为正式文章
            Long articleId = articleDraftService.publishDraft(id);
            
            // 确保返回的articleId不为null
            if (articleId == null) {
                log.warn("发布草稿成功但未获取到文章ID，设置默认值");
                return AppResult.success(1L); // 返回默认值1而不是null
            }
            
            log.info("草稿发布成功，草稿ID: {}，新文章ID: {}", id, articleId);
            return AppResult.success(articleId);
        } catch (Exception e) {
            log.error("发布草稿失败", e);
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
    }
    
    @ApiOperation("将文章保存为草稿")
    @PostMapping("/saveArticleAsDraft")
    public AppResult<Long> saveArticleAsDraft(
            HttpServletRequest request,
            @ApiParam("板块ID") @RequestParam("boardId") @NotNull Long boardId,
            @ApiParam("文章标题") @RequestParam("title") String title,
            @ApiParam("文章内容") @RequestParam("content") String content,
            @ApiParam("文章标签") @RequestParam(value = "tags", required = false) String tags,
            @ApiParam("文章摘要") @RequestParam(value = "summary", required = false) String summary) {
        
        // 获取当前用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        
        // 校验用户状态
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        
        // 校验板块
        Board board = boardService.selectById(boardId);
        if (board == null || board.getDeleteState() == 1 || board.getState() == 1) {
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        
        // 创建文章对象
        Article article = new Article();
        article.setUserId(user.getId());
        article.setBoardId(boardId);
        article.setTitle(title);
        article.setContent(content);
        article.setTags(tags);
        article.setSummary(summary);
        
        try {
            Long draftId = articleDraftService.saveArticleAsDraft(article);
            return AppResult.success(draftId);
        } catch (Exception e) {
            log.error("将文章保存为草稿失败", e);
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
    }
    
    @ApiOperation("获取用户草稿数量")
    @GetMapping("/count")
    public AppResult<Integer> countUserDrafts(HttpServletRequest request) {
        
        // 获取当前用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        
        try {
            int count = articleDraftService.countUserDrafts(user.getId());
            return AppResult.success(count);
        } catch (Exception e) {
            log.error("获取用户草稿数量失败", e);
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
    }
} 